<?php

namespace App\Http\Controllers;

use App\GoodOrder;
use App\GoodRecordInput;
use App\GoodReturn;
use App\GoodSale;
use App\GoodStackDown;
use App\GoodStackRecord;
use App\GoodStackUp;
use App\GoodWholeSaleReturn;
use App\GoodWholeSaleReturnRecord;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\GoodInput;
use App\Good;
use App\GoodColor;
use App\GoodColorSize;
use App\GoodStoreMember;
use App\GoodStore;
use Validator;
class GoodStockController extends Controller
{
    //
    public function input(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'list' => 'required'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        $lists = json_decode($request->list);
        foreach ($lists as $list) {
            $input = new GoodInput();
            $good = Good::find($list->goodId);
            $input->goodName = $good->name;
            $input->price = $list->price;
            $input->provider = $good->provider;
            $input->description = $list->description;
            $input->operatorId = $request->userId;
            $input->storeId = $member->storeId;
            $input->number = $list->number;

            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            if ($color == null) {
                $color = new GoodColor();
                $color->name = $list->color;
                $color->picture = '';
                $color->goodId = $good->id;
                $color->save();
                $size = new GoodColorSize();
                $size->colorId = $color->id;
                $size->size = $list->size;
                $size->number = $list->number;
                $size->inputPrice = $list->price;
                $size->onStackNumber = 0;
                $size->isDiscount = 0;
                $size->save();
            } else {
                $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
                if ($size == null) {
                    $size = new GoodColorSize();
                    $size->colorId = $color->id;
                    $size->size = $list->size;
                    $size->number = $list->number;
                    $size->inputPrice = $list->price;
                    $size->onStackNumber = 0;
                    $size->isDiscount = 0;
                    $size->save();
                } else {
                    $size->number += $list->number;
                    $size->inputPrice = $list->price;
                    $size->save();
                }
            }
            $input->colorName = $color->name;
            $input->sizeName = $size->size;
            $input->numberAfter = $size->number;
            $input->onStackNumberAfter = $size->onStackNumber;
            $input->save();

            $input->date = $input->created_at->format('Y-m-d');
            $input->save();

            $record = GoodRecordInput::where('date', $input->date)
                ->where('operatorId', $request->userId)
                ->where('goodName', $input->goodName)
                ->where('provider', $input->provider)
                ->first();

            if ($record == null) {
                $record = new GoodRecordInput();
                $record->date = $input->date;
                $record->operatorId = $input->operatorId;
                $record->provider = $input->provider;
                $record->goodName = $input->goodName;
                $record->stockNumber = $input->numberAfter;
                $record->inputNumber = $input->number;
                $record->storeId = $member->storeId;
                $record->save();
                $input->recordId = $record->id;
                $input->save();
            } else {
                $record->stockNumber = $input->numberAfter + $input->onStackNumberAfter;
                $record->inputNumber += $input->number;
                $record->save();
            }
        }
        $this->returnEcho();
    }

    public function ret(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'list' => 'required'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $lists = json_decode($request->list);
        foreach ($lists as $list) {
            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
            if ($size->number + $size->onStackNumber < $list->number) {
                echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => 0]);
                return ;
            }
        }
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        foreach ($lists as $list) {
            $ret = new GoodReturn();
            $good = Good::find($list->goodId);
            $ret->goodName = $good->name;
            $ret->price = $list->price;
            $ret->provider = $good->provider;
            $ret->colorName = $list->color;
            $ret->sizeName = $list->size;
            $ret->number = $list->number;
            $ret->operatorId = $request->userId;

            $ret->storeId = $member->storeId;
            $ret->description = $list->description;
            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
            if ($size->number + $size->onStackNumber < $list->number) {
                echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => []]);
                return ;
            }
            else if ($size->number < $list->number)
            {
                $size->number = 0;
                $size->onStackNumber -= ($list->number - $size->number);
            }
            else {
                $size->number -= $list->number;
            }
            $ret->numberAfter = $size->number;
            $ret->onStackNumberAfter = $size->onStackNumber;
            $size->save();
            $ret->save();

            $ret->date = $ret->created_at->format('Y-m-d');
            $ret->save();

            $record = GoodRecordInput::where('date', $ret->date)
                ->where('operatorId', $request->userId)
                ->where('goodName', $ret->goodName)
                ->where('provider', $ret->provider)
                ->first();

            if ($record == null) {
                $record = new GoodRecordInput();
                $record->date = $ret->date;
                $record->operatorId = $ret->operatorId;
                $record->provider = $ret->provider;
                $record->goodName = $ret->goodName;
                $record->stockNumber = $ret->numberAfter;
                $record->returnNumber = $ret->number;
                $record->storeId = $member->storeId;
                $record->save();
                $ret->recordId = $record->id;
                $ret->save();
            } else {
                $record->stockNumber = $ret->numberAfter + $ret->onStackNumberAfter;
                $record->returnNumber += $ret->number;
                $record->save();
            }

        }
        $this->returnEcho();
    }

    public function wholeSaleReturn(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'list' => 'required'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        $lists = json_decode($request->list);
        foreach ($lists as $list) {
            $input = new GoodWholeSaleReturn();
            $good = Good::find($list->goodId);
            $input->goodName = $good->name;
            $input->price = $list->price;
            $input->buyer = $list->buyer;
            $input->description = $list->description;
            $input->operatorId = $request->userId;

            $input->storeId = $member->storeId;
            $input->number = $list->number;

            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            if ($color == null) {
                $color = new GoodColor();
                $color->name = $list->color;
                $color->picture = '';
                $color->goodId = $good->id;
                $color->save();
                $size = new GoodColorSize();
                $size->colorId = $color->id;
                $size->size = $list->size;
                $size->number = $list->number;
                $size->inputPrice = $list->price;
                $size->onStackNumber = 0;
                $size->isDiscount = 0;
                $size->save();
            } else {
                $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
                if ($size == null) {
                    $size = new GoodColorSize();
                    $size->colorId = $color->id;
                    $size->size = $list->size;
                    $size->number = $list->number;
                    $size->inputPrice = $list->price;
                    $size->onStackNumber = 0;
                    $size->isDiscount = 0;
                    $size->save();
                } else {
                    $size->number += $list->number;
                    $size->inputPrice = $list->price;
                    $size->save();
                }
            }
            $input->colorName = $color->name;
            $input->sizeName = $size->size;
            $input->numberAfter = $size->number;
            $input->onStackNumberAfter = $size->onStackNumber;
            $input->save();

            $input->date = $input->created_at->format('Y-m-d');
            $input->save();

            $record = GoodWholeSaleReturnRecord::where('date', $input->date)
                ->where('operatorId', $request->userId)
                ->where('goodName', $input->goodName)
                ->where('buyer', $input->buyer)
                ->first();

            if ($record == null) {
                $record = new GoodWholeSaleReturnRecord();
                $record->date = $input->date;
                $record->operatorId = $input->operatorId;
                $record->buyer = $input->buyer;
                $record->goodName = $input->goodName;
                $record->stockNumber = $input->numberAfter;
                $record->inputNumber = $input->number;
                $record->storeId = $member->storeId;
                $record->save();
                $input->recordId = $record->id;
                $input->save();
            } else {
                $record->stockNumber = $input->numberAfter;
                $record->inputNumber += $input->number;
                $record->save();
            }


        }
        $this->returnEcho();
    }

    public function sale(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'list' => 'required'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $lists = json_decode($request->list);
        foreach ($lists as $list) {
            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
            if ($size->number + $size->onStackNumber < $list->number) {
                echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => []]);
                return ;
            }
        }
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        foreach ($lists as $list) {
            $sale = new GoodSale();
            $good = Good::find($list->goodId);
            $sale->goodId = $list->goodId;
            $sale->goodName = $good->name;
            $sale->price = $list->price;
            $sale->colorName = $list->color;
            $sale->sizeName = $list->size;
            $sale->number = $list->number;
            $sale->operatorId = $request->userId;

            $sale->storeId = $member->storeId;
            $sale->description = $list->description;


            $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->color)->first();
            $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->size)->first();
            if ($size->number + $size->onStackNumber < $list->number) {
                echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => 0]);
                return ;
            }
            else if ($size->onStackNumber < $list->number)
            {
                $size->onStackNumber = 0;
                $size->number -= ($list->number - $size->onStackNumber);
            }
            else {
                $size->onStackNumber -= $list->number;
            }
            $sale->numberAfter = $size->number;
            $size->save();
            $sale->save();
            $sale->date = $sale->created_at->format('Y-m-d');
            $sale->save();

        }
        $this->returnEcho(200, '', 1);
    }

    public function up(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|integer',
            'color' => 'required',
            'number' => 'required',
            'size' => 'required',
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $good = Good::find($request->goodId);
        $color = GoodColor::where('goodId', $good->id)->where('name', $request->color)->first();
        $size = GoodColorSize::where('colorId', $color->id)->where('size', $request->size)->first();

        $record = new GoodStackUp();
        $record->operatorId = $request->userId;
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        $record->storeId = $member->storeId;
        $record->goodName = $good->name;
        $record->colorName = $color->name;
        $record->sizeName = $size->size;
        $record->number = $request->number;
        if ($size->number < $request->number) {
            echo json_encode(['status' => 403, 'errmsg' => 'number is too large', 'data' => []]);
            return ;
        }

        $size->onStackNumber += $request->number;
        $size->number -= $request->number;
        $record->onStackNumberAfter = $size->onStackNumber;
        $record->numberAfter = $size->number;
        $size->save();
        $record->save();
        $record->date = $record->created_at->format('Y-m-d');
        $record->save();

        $stack = GoodStackRecord::where('date', $record->date)
            ->where('operatorId', $request->userId)
            ->where('goodName', $record->goodName)
            ->first();

        if ($stack == null) {
            $stack = new GoodStackRecord();
            $stack->date = $record->date;
            $stack->operatorId = $request->userId;
            $stack->goodName = $record->goodName;
            $stack->stockNumber = $record->numberAfter;
            $stack->upNumber = $record->number;
            $stack->storeId = $member->storeId;
            $stack->save();
        } else {
            $stack->upNumber += $record->number;
            $stack->stockNumber = $record->numberAfter;
            $stack->save();
        }

        echo json_encode(['status'=>200, 'errmsg' => '', 'data' => 1]);
    }

    public function down(Request $request) {
        $validator = Validator::make($request->all(), array(
            'goodId' => 'required|integer',
            'color' => 'required',
            'number' => 'required',
            'size' => 'required',
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $good = Good::find($request->goodId);
        $color = GoodColor::where('goodId', $good->id)->where('name', $request->color)->first();
        $size = GoodColorSize::where('colorId', $color->id)->where('size', $request->size)->first();

        $record = new GoodStackDown();
        $record->operatorId = $request->userId;
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        $record->storeId = $member->storeId;
        $record->goodName = $good->name;
        $record->colorName = $color->name;
        $record->sizeName = $size->size;
        $record->number = $request->number;
        if ($size->onStackNumber < $request->number) {
            echo json_encode(['status' => 403, 'errmsg' => 'number is too large', 'data' => []]);
            return ;
        }

        $size->onStackNumber -= $request->number;
        $size->number += $request->number;
        $record->onStackNumberAfter = $size->onStackNumber;
        $record->numberAfter = $size->number;
        $size->save();
        $record->save();
        $record->date = $record->created_at->format('Y-m-d');
        $record->save();

        $stack = GoodStackRecord::where('date', $record->date)
            ->where('operatorId', $request->userId)
            ->where('goodName', $record->goodName)
            ->first();

        if ($stack == null) {
            $stack = new GoodStackRecord();
            $stack->date = $record->date;
            $stack->operatorId = $request->userId;
            $stack->goodName = $record->goodName;
            $stack->stockNumber = $record->numberAfter;
            $stack->downNumber = $record->number;
            $stack->storeId = $member->storeId;
            $stack->save();
        } else {
            $stack->downNumber += $record->number;
            $stack->stockNumber = $record->numberAfter;
            $stack->save();
        }

        echo json_encode(['status'=>200, 'errmsg' => '', 'data' => 1]);
    }

    public function order(Request $request) {
        $validator = Validator::make($request->all(), array(
            'list' => 'required',
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;

        $lists = json_decode($request->list);

        foreach ($lists as $list) {
            $sale = new GoodOrder();
            $description = '';
            if (array_key_exists("description", $list))
                $description = $list->description;
            $sale->goodId = $list->goodId;
            $good = Good::find($list->goodId);
            $sale->goodName = $good->name;
            $sale->colorName = $list->color;
            $sale->sizeName = $list->size;
            $sale->number = $list->number;
            $sale->price = $list->price;
            $sale->operatorId = $request->userId;
            $member = GoodStoreMember::where('memberId', $request->userId)->first();
            $sale->storeId = $member->storeId;
            $sale->buyer = $list->buyer;
            $sale->orderTime = $list->orderTime;
            $sale->payTime = '';
            $sale->description = $description;
            $sale->save();
        }
        echo json_encode(['status'=>200, 'errmsg' => '', 'data' => 1]);
    }

    public function getOrder(Request $request) {
        $validator = Validator::make($request->all(), array(
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255',
            'goodId' => 'required',
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;
        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        if ($request->memberId == null) {
            $inputs = GoodOrder::where('goodId', $request->goodId)->where('storeId', $member->storeId)->whereBetween('created_at', [$request->start, $request->end])->paginate($request->perPage);
            $pageData = [
                "count" => $inputs->count(),
                "currentPage" => $inputs->currentPage(),
                "lastPage" => $inputs->lastPage()
            ];
            $data = [];
            foreach ($inputs as $input) {
                array_push($data, [
                    "id" => $input->id,
                    "time" => $input->updated_at->format('Y-m-d H:i'),
                    "goodId" => $input->goodId,
                    "name" => $input->goodName,
                    "color" => $input->colorName,
                    "size" => $input->sizeName,
                    "orderTime" => $input->orderTime,
                    "payTime" => $input->payTime,
                    "buyer" => $input->buyer,
                    "number" => $input->number,
                    "operatorId" => $input->operatorId,
                    "operatorName" => $member->name,
                    "description" => $input->description
                ]);
            }
            echo json_encode(['status' => 200, 'errmsg' => '', 'data' =>['pageData' => $pageData, 'list' => $data]]);
        }
        else {
            $inputs = GoodOrder::where('goodId', $request->goodId)->where('storeId', $member->storeId)->whereBetween('created_at', [$request->start, $request->end])->paginate($request->perPage);
            $pageData = [
                "count" => $inputs->count(),
                "currentPage" => $inputs->currentPage(),
                "lastPage" => $inputs->lastPage()
            ];
            $data = [];
            foreach ($inputs as $input) {
                array_push($data, [
                    "id" => $input->id,
                    "time" => $input->updated_at->format('Y-m-d H:i'),
                    "goodId" => $input->goodId,
                    "name" => $input->goodName,
                    "color" => $input->colorName,
                    "size" => $input->sizeName,
                    "orderTime" => $input->orderTime,
                    "payTime" => $input->payTime,
                    "buyer" => $input->buyer,
                    "number" => $input->number,
                    "operatorId" => $input->operatorId,
                    "operatorName" => $member->name,
                    "description" => $input->description
                ]);
            }
            echo json_encode(['status' => 200, 'errmsg' => '', 'data' =>['pageData' => $pageData, 'list' => $data]]);
        }
    }

    public function payOrder(Request $request) {
        $validator = Validator::make($request->all(), array(
            'orderIds' => 'required',
            'userId' => 'required|max:255',
            'sessionId' => 'required|max:255'
        ));
        if ($validator->fails()) {
            $this->validatorError($validator);
            return ;
        }
        if (!$this->sessionValidate($request->sessionId))
            return ;


        $member = GoodStoreMember::where('memberId', $request->userId)->first();
        $store = GoodStore::find($member->storeId);
        $type = 1;
        if ($store->type == 0)
            $type = 0;
        $orderIds = json_decode($request->orderIds);
        $payTime = '';

        if ($type == 0) {
            foreach ($orderIds as $orderId) {
                $order = GoodOrder::find($orderId);
                $good = Good::find($order->goodId);
                $color = GoodColor::where('goodId', $good->id)->where('name', $order->colorName)->first();
                $size = GoodColorSize::where('colorId', $color->id)->where('size', $order->sizeName)->first();
                if ($size->number + $size->onStackNumber < $order->number) {
                    echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => []]);
                    return ;
                }
            }
            foreach ($orderIds as $orderId) {
                $order = GoodOrder::find($orderId);
                $sale = new GoodSale();
                $good = Good::find($order->goodId);
                $sale->goodName = $good->name;
                $sale->price = $order->price;
                $sale->colorName = $order->colorName;
                $sale->sizeName = $order->sizeName;
                $sale->number = $order->number;
                $sale->operatorId = $request->userId;
                $member = GoodStoreMember::where('memberId', $request->userId)->first();
                $sale->storeId = $member->storeId;
                $sale->description = $order->description;

                $color = GoodColor::where('goodId', $order->goodId)->where('name', $order->colorName)->first();
                $size = GoodColorSize::where('colorId', $color->id)->where('size', $order->sizeName)->first();
                if ($size->number + $size->onStackNumber < $order->number) {
                    echo json_encode(['status' => 403, 'errmsg' => 'number is too large' , 'data' => 0]);
                    return ;
                }
                else if ($size->onStackNumber < $order->number)
                {
                    $size->onStackNumber = 0;
                    $size->number -= ($order->number - $size->onStackNumber);
                }
                else {
                    $size->onStackNumber -= $order->number;
                }
                $size->save();
                $sale->save();
                $order->payTime = 1;
                $order->save();
                $payTime = $order->updated_at->format('Y-m-d H:i');
                $order->payTime = $payTime;
                $order->save();
            }

        }
        else {
            foreach ($orderIds as $orderId) {
                $list = GoodOrder::find($orderId);
                $input = new GoodInput();
                $good = Good::find($list->goodId);
                $input->goodName = $good->name;
                $input->price = $list->price;
                $input->provider = $good->provider;
                $input->description = $list->description;
                $input->operatorId = $request->userId;
                $member = GoodStoreMember::where('memberId', $request->userId)->first();
                $input->storeId = $member->storeId;
                $input->number = $list->number;

                $color = GoodColor::where('goodId', $list->goodId)->where('name', $list->colorName)->first();
                if ($color == null) {
                    $color = new GoodColor();
                    $color->name = $list->colorName;
                    $color->picture = '';
                    $color->goodId = $good->id;
                    $color->save();
                    $size = new GoodColorSize();
                    $size->colorId = $color->id;
                    $size->size = $list->sizeName;
                    $size->number = $list->number;
                    $size->inputPrice = $list->price;
                    $size->onStackNumber = 0;
                    $size->isDiscount = 0;
                    $size->save();
                } else {
                    $size = GoodColorSize::where('colorId', $color->id)->where('size', $list->sizeName)->first();
                    if ($size == null) {
                        $size = new GoodColorSize();
                        $size->colorId = $color->id;
                        $size->size = $list->sizeName;
                        $size->number = $list->number;
                        $size->inputPrice = $list->price;
                        $size->onStackNumber = 0;
                        $size->isDiscount = 0;
                        $size->save();
                    } else {
                        $size->number += $list->number;
                        $size->inputPrice = $list->price;
                        $size->save();
                    }
                }
                $input->colorName = $color->name;
                $input->sizeName = $size->size;
                $input->numberAfter = $size->number;
                $input->onStackNumberAfter = $size->onStackNumber;
                $input->save();
                $list->payTime = 1;
                $list->save();
                $payTime = $list->updated_at->format('Y-m-d H:i');
                $list->payTime = $payTime;
                $list->save();
            }
        }


        echo json_encode(['status' => 200, 'errmsg' => '', 'data' => ["payTime" => $payTime]]);
    }
}
